<template>
    <div>
        递归函数
        <el-tree :data="familyData" show-checkbox node-key="nid" default-expanded-all
            :default-checked-keys="defaultCheckedKeys" :props="{ label: 'name' }" ref="tree">
        </el-tree>


        <el-button @click="getCheckedNid">从树上获取选中的节点id</el-button>
    </div>
</template>


<script>
export default {
    name: "DiGui",
    data() {
        return {
            familyData: [
                {
                    nid: 1,
                    name: "你",
                    children: [
                        {
                            nid: 2,
                            name: "你的孩子1",
                            children: [
                                {
                                    nid: 3,
                                    name: "你的孙子1",
                                },
                                {
                                    nid: 4,
                                    name: "你的孙子2",
                                },
                                {
                                    nid: 5,
                                    name: "你的孙子3",
                                }
                            ],
                        },
                        {
                            nid: 6,
                            name: "你的孩子2",
                        },
                    ],
                },
            ],
            defaultCheckedKeys: [],
        }
    },
    methods:{
        getCheckedNid(){
            console.log(this.$refs.tree.getCheckedKeys());
            console.log(this.$refs.tree.getHalfCheckedKeys());
            console.log(this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()));
        }
    },
    created() {
        //获取一个已经呗选中的孩子的数据
        const getChildrenchecked = {
            nid: 1,
            name: "你",
            children: [
                {
                    nid: 2,
                    name: "你的孩子1",
                    children: [
                        {
                            nid: 3,
                            name: "你的孙子1",
                        },
                    ],
                },
                {
                    nid: 6,
                    name: "你的孩子2",
                },
            ],
        };


        let arr = [];
        function getTreeNids(treeData) {
            if (!treeData.children) return arr.push(treeData.nid);
            // arr.push(treeData.nid);
            treeData.children.forEach(
                child => {
                    getTreeNids(child)
                });
        }
        // getTreeNids(this.familyData[0]);
        getTreeNids(getChildrenchecked);
        this.defaultCheckedKeys = arr;
    }
}
</script>